package com.jar.springbootsecuritydemo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jar.springbootsecuritydemo.config.SecurityUserFactory;
import com.jar.springbootsecuritydemo.mapper.SysRoleMapper;
import com.jar.springbootsecuritydemo.mapper.SysUserMapper;
import com.jar.springbootsecuritydemo.pojo.bo.SecurityUser;
import com.jar.springbootsecuritydemo.pojo.entity.SysRole;
import com.jar.springbootsecuritydemo.pojo.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 将SpringSecurity中的用户管理和数据库的管理员对应起来
 * 相当于userDao
 */
@Service
public class SecurityUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    /**
     * @param username 浏览器输入的用户名【需要保证用户名的唯一性】
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public SecurityUser loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUser user = sysUserMapper.selectOne(
                new QueryWrapper<SysUser>()
                        .eq(SysUser.COL_USER_NAME, username)
                        .last("LIMIT 1")
        );

        if (user != null) {
            //查询出角色信息封装到admin中
            List<String> roleNames = new ArrayList<>();
            SysRole sysRole = sysRoleMapper.selectById(user.getUserId());
            roleNames.add(sysRole.getRoleName());
            user.setSysRoles(roleNames);
            return SecurityUserFactory.create(user);
        }
        return null;
    }

}
